function unique(arr){
 //Set数据结构，它类似于数组，其成员的值都是唯一的
 return Array.from(new Set(arr)); // 利用Array.from将Set结构转换成数组
}
function doUPLoadFile(result){
    featureNames = result.feature_names;

    for(var i = 0; i < featureNames.length; i++) {
	    featureNameImportance[i]=true;
    }
    drawFeatureImportance(featureNames,featureNameImportance);
    dataSet = [];
    n_feature = featureNames.length;
    typeList = [];
    typeArray=[];
    dTable.init(featureNames);
    tableData = [];
    for(var i = 0;i<result.data.length;i++)
    {
        dataRow =[];
        showRow= [];
        dataRow.push(i);
        for(var j = 0;j<n_feature;j++)
        {
            dataRow.push(parseFloat(result.data[i][j]));
            showRow.push(parseFloat(result.data[i][j]));
        }
        dataRow.push(0);
        typeList.push("0");
        tableData.push(dataRow);
        dataSet.push(showRow);
    }

    let clusterInfo = d3.select("#dataInfoDiv").html("");
    clusterInfo.append("div").text("Dataset Size："+dataSet.length)
    clusterInfo.append("div").text("Feature Number："+n_feature)
   // clusterInfo.append("<div>特征个数:"+n_feature+"</div>")
    // clusterInfo.append("div").text("特征个数"+n_feature)
    dTable.updateTable(tableData);
    options = d3.select("#select_Attribute").selectAll("option").data(featureNames);
    options.enter().append("option").attr("value",(d,i)=>i).text((d,i)=>d);


}
function  showTypeInfo(){
    chart = new Chart();
    chart.scaleX = d3.scaleLinear()
                    .domain([0, d3.max(typeInfo)])
                    .range([0, 150]);
    div =  d3.select('#typeView').selectAll("div").remove();
   for (let i = 0;i<typeInfo.length;i++)
   {
       div =  d3.select('#typeView').append("div");
       div.append("input").attr("type",'checkbox').attr("title","").attr("lay-filter","type").attr("value",i).attr("lay-skin","primary").attr("checked",1);
       div.append("div").style("display","inline-block").style("width","130px").style("height","20px").style("vertical-align","middle")
            .append("div").style("width",chart.scaleX(typeInfo[i])+"px").style("height","20px").style("background",chart._colors[i+1]).text(typeInfo[i]);

   }

    layui.form.render();
    layui.form.on('checkbox(type)', function(data){
            useType[data.value] = data.elem.checked;
            scatterUseType=[];
            for (let i =0;i<useType.length;i++)
            {

                    scatterUseType[i] = useType[i];

            }
            drawScatterChart(scatterData,typelist,0,1);
        });
}

function showClusterResult(){

        var test_url = "/cluster/";
        a = $("#cluster_num").val();
        b = $("#cluster_Overlap").val();
        c = $("#cluster_Outlier").val();
        if(a == "" || b == "" || c=="")
        {
            layer.msg('请输入聚类参数');
            return;
        }
        $.ajax({
            type: "post",
            //async: false,
            url: test_url,
            data: {
                'out_val': c,
                'over_val': b,
                'num_val':a,
                "showData":JSON.stringify(dataSet),
                "n_feature":n_feature,
            },
            //JSON.stringify(d.ind),
            dataType: "json",
            success: function (dataRes) {
                //console.log(dataRes);
                doUPLoadFile(dataRes);
                typelist = dataRes['type'];
                n_cluster = unique(typelist).length;
                for (let i=0;i<n_cluster;i++)
                {
                    typeInfo[i] = 0;
                    useType[i] = true;
                    scatterUseType[i] = true;
                }
                for (let i =0;i<typelist.length;i++)
                {
                    typelist[i]= parseInt(typelist[i]);
                    typeInfo[typelist[i]]++;
                }

                showTypeInfo();
                drawBasicScatter();
                dTable.upDataType();


            }
        });

    }

function  drawFeatureImportance(featureNames,featureImportance){
    // featureNames.sort(function (a,b){
    //      return  featureImportance[featureNames.indexOf(b)]-featureImportance[featureNames.indexOf(a)] ;
    // });-
    // 6ort(function (a,b){
    //     return b-a;
    // });
    d3.select("#AttributeImportanceView").selectAll("div").remove();
    divEnter = d3.select("#AttributeImportanceView").selectAll("div").data(featureNames).enter().append("div");


    divEnter.each(function (d,i){

          d3.select(this).append("input").attr("type",'checkbox').attr("title",d).attr("lay-filter","type1").attr("value",i)
              .attr("lay-skin","primary").attr("checked",1);

    });
    layui.form.render();
    layui.form.on('checkbox(type1)', function(data){
             featureImportance[data.value] = data.elem.checked;
        });

}

function  makeExplanation(){
    analyTypelist = [];
    analyDataSet = [];
    preTypelist= [];
    preTypeIndex=[];
    for (let i=0;i<typelist.length;i++)
    {
        if (useType[typelist[i]])
        {
            analyDataSet.push(dataSet[i]);
            analyTypelist.push(typelist[i]);
            preTypelist.push(0);
            preTypeIndex.push(i);
        }
    }
    // typeColor = [];
    // analy_cluster =0 ;
    // for (let i = 0;i<useType.length;i++)
    // {
    //     if (useType[i])
    //     {
    //         typeColor.push(i+1);
    //         analy_cluster++;
    //     }
    // }

    $.ajax({
        type:"POST",
        url:"/getRuleTree/",
        data:{
            "data":JSON.stringify(analyDataSet ),
            "type":JSON.stringify(analyTypelist ),
            "featureImport":JSON.stringify(featureNameImportance)
        },
        success:function (dataRes) {
            var temp ={};
            splitTree = dataRes;
            // feature = dataRes['feature'];
            // var right=dataRes['children_right'];
            // var left=dataRes['children_left'];
            // var threshold=dataRes['threshold'];
            // var value = dataRes['value']
            // for(var i = 0;i<threshold.length;i++){
            //     threshold[i] = threshold[i].toFixed(2);
            // }
            // treeinfo = makeTreeData(feature,right,left,threshold,value,analyDataSet);
            treeinfo = newMakeTreeData(splitTree,analyDataSet,analyTypelist,"root",preTypeIndex);
            drawBasicTreeChart(treeinfo);
            drawMatrix();

        }
    });
}

async function splitTheNode() {
    splitNode.mistake = selectsplitmistake;
    splitNode.feature = selectsplitFeature;
    splitNode.threshold = selectsplitValue;
    splitNode.fouse =1;
    splitNode.children = [];
    let centers = splitNode.center;
    let data = splitNode.data;
    let type = splitNode.typelist;
    let leftdata = [];
    let rightdata = [];
    let leftType = [];
    let rightType = []
    let leftNode = {};
    let rightNode = {};
    let leftcenter = {};
    let rightcenter = {};
    for (let i in centers) {
        if (centers[i][selectsplitFeature] <= selectsplitValue)
            leftcenter[i] = centers[i];
        else
            rightcenter[i] = centers[i];
    }
    for (let i = 0; i < data.length; i++) {
        if (data[i][selectsplitFeature] <= selectsplitValue) {
            leftdata.push(data[i]);
            leftType.push(type[i]);
        } else {
            rightdata.push(data[i]);
            rightType.push(type[i]);
        }
    }
    leftNode.center = leftcenter;
    if (Object.keys(leftcenter).length > 1) {
         await splitThisNode(leftNode, leftdata, leftType, leftcenter);
    }
    rightNode.center = rightcenter;
    if (Object.keys(rightcenter).length > 1) {
         await splitThisNode(rightNode, rightdata, rightType, rightcenter);
     }
    splitNode.children.push(leftNode);
    splitNode.children.push(rightNode);
    treeinfo = newMakeTreeData(splitTree, analyDataSet, analyTypelist, "root", preTypeIndex);
    drawBasicTreeChart(treeinfo);
}
async function splitThisNode(thisnode,data,type,centers) {

    let splitValuse = await d3.json("/getSplitFeatureOrder/", {
        method: 'POST',
        body: JSON.stringify({data: data, type: type, center: centers})
    });
    let  tempsplitData = splitValuse.data;

    tempsplitData.sort(function (a,b){
       return  d3.ascending(a.mistake,b.mistake);
    });
    thisnode.mistake = tempsplitData[0].mistake;
    thisnode.feature =  tempsplitData[0].index;
    thisnode.threshold =  tempsplitData[0].bestValue;
    thisnode.children= [];
    let leftdata=[];
    let rightdata=[];
    let leftType=[];
    let rightType=[]
    let leftNode={};
    let rightNode={};
    let leftcenter={};
    let rightcenter={};
    for (let i in centers)
    {
        if (centers[i][thisnode.feature]<=thisnode.threshold)
            leftcenter[i]= centers[i];
        else
            rightcenter[i] = centers[i];
    }
    for(let i=0;i<data.length;i++)
    {
        if (data[i][thisnode.feature]<=thisnode.threshold)
        {
            leftdata.push(data[i]);
            leftType.push(type[i]);
        }
        else
        {
            rightdata.push(data[i]);
            rightType.push(type[i]);
        }
    }
    leftNode.center = leftcenter;
    if (Object.keys(leftcenter).length>1)
    {
        await splitThisNode(leftNode,leftdata,leftType,leftcenter);
    }
    rightNode.center = rightcenter;
    if (Object.keys(rightcenter).length>1)
    {
         await splitThisNode(rightNode,rightdata,rightType,rightcenter);
    }
    thisnode.children.push(leftNode);
    thisnode.children.push(rightNode);
}